//
//  M1EditInformationTextFieldVC.m
//  NewMarryU
//
//  Created by Cedar on 2018/7/21.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1EditInformationTextFieldVC.h"
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
@interface M1EditInformationTextFieldVC ()<UITextFieldDelegate>
{
    BOOL isName;
    NSInteger Max_Num_TextView;
}

@property (nonatomic, strong) UITextField *textField;

@end

@implementation M1EditInformationTextFieldVC

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = self.titleStr;
        
    [self m1_createRightBarButtonItem:@"保存" titleColor:m1_color(0x333333) action:@selector(m1_rightAction)];
    
    if ([self.titleStr isEqualToString:@"昵称"]) {
        isName = YES;
    }
    
    if (isName) {
        Max_Num_TextView = 12;
    }else{
        Max_Num_TextView = 30;
    }
    
    [self createTextField];
    
    if ([self.titleStr isEqualToString:@"微信号"]){
        self.textField.keyboardType = UIKeyboardTypeASCIICapable;
    }else{
        self.textField.keyboardType = UIKeyboardTypeDefault;
    }
}


- (void) m1_rightAction{
    
    NSString *str = [_textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if ([str length] > 0) {
        if ([self.titleStr isEqualToString:@"微信号"]) {
            WEAKSELF;
        
            [M1HttpNet requestWithMethod:m1_update_info_url params:@{@"wechat":str} success:^(id resDic, NSInteger code, NSString *message) {
                if (weakSelf.returnText) {
                    weakSelf.returnText(str);
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            } fail:^(id resDic, NSInteger code, NSString *message) {
                [M1Alert m1_alertWithTitle:nil message:message];
            } showAni:YES];
        }else{
            if (_returnText) {
                _returnText(str);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    // 不让输入表情
    if ([self.textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            [M1Alert m1_alertWithTitle:nil message:@"不支持Emoji表情"];
            return NO;
        }

        if ([string m1_includEmoji]) {
            [M1Alert m1_alertWithTitle:nil message:@"不支持Emoji表情"];
            return NO;
        }
    }
    
    return YES;
    
}

- (void)textFieldChange:(NSNotification *)note{
    //取到高亮部分范围
    UITextRange *selectedRange = [self.textField markedTextRange];
    //取到高亮部分
    UITextPosition *position = [self.textField positionFromPosition:selectedRange.start offset:0];
    //如果取不到高亮部分,代表没有拼音
    if (!position){
        NSString *tf = self.textField.text;
        
        if ([tf length] > Max_Num_TextView) {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
            for(int i =0; i < [tf length]; i++)
            {
                [array addObject:[tf substringWithRange:NSMakeRange(i,1)]];
                
            }
            float length = 0;
            for (int i = 0; i<array.count ; i++) {
                NSString *news = array[i];
                length += [news length];
                if (length > Max_Num_TextView) {
                    tf = [tf substringToIndex:i];
                    if (isName) {
//                        [AlertUtil showTipAlertViewWith:self title:@"提示" message:@"昵称最长请不要超过6个汉字" buttonTitle:@"知道了" buttonStyle:KAlertActionStyleDefault];
                        
                    }else{
//                        [self createHintAlert:[NSString stringWithFormat:@"最多只能输入%ld个字符长度!请您合理安排内容!", Max_Num_TextView]];
                    }
                    break;
                }
            }
        }
        
        self.textField.text = tf;
        
    }else{
        // 高亮部分
    }
}


#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChange:(UITextField *)textField{
    
}


#pragma  mark - createUI
- (void)createTextField{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, m1_NAV_HEIGHT + 20, SCREENWIDTH, 50)];
    bgView.backgroundColor = m1_color(0xFFFFFF);
    [self.view addSubview:bgView];
    
    NSString *name;
    if ([self.textStr isEqualToString:@"请设置昵称"]) {
        name = @"";
    }else{
        name = self.textStr;
    }
    
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(15, 0, SCREENWIDTH - 30, 50)];
    _textField.backgroundColor = m1_color(0xFFFFFF);
    _textField.placeholder = [NSString stringWithFormat:@"请输入%@", _titleStr];
    _textField.text = name;
    _textField.textColor = m1_color(0x666666);
    _textField.font =m1_font(14);
    _textField.delegate = self;
    _textField.returnKeyType = UIReturnKeyDone;
    _textField.clearButtonMode = UITextFieldViewModeAlways;
    [bgView addSubview:_textField];
    //    if ([_titleStr isEqualToString:@"联系电话"]) {
    //        _textField.keyboardType = UIKeyboardTypeNumberPad;
    //    }else{
    //        _textField.keyboardType = UIKeyboardTypeDefault;
    //    }
    
    [_textField becomeFirstResponder];
}

- (void) m1_createRightBarButtonItem:(NSString *)title titleColor:(UIColor *)color action:(SEL)action{
    CGFloat width;
    if ([title length] > 2) {
        width = 70;
    }else{
        width = 40;
    }
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, width, 44);
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateNormal];
    button.titleLabel.font = m1_font(16);
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBtn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightBtn;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
